<!-- src\views\machine\MachineAdd.vue -->
<template>
  <div class="add-machine">
    <el-card class="add-card">
      <template #header>
        <div class="card-header">
          <span>新增机器</span>
        </div>
      </template>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="add-form">
        <el-form-item label="机器编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入机器编号" />
        </el-form-item>
        <el-form-item label="机器类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" @change="onTypeChange">
            <el-option v-for="group in agriculturalDataStore.getAgriculturalMachines" :key="group.title"
              :label="group.title" :value="group.title" />
          </el-select>
        </el-form-item>
        <el-form-item label="机器名称" prop="name">
          <el-select v-model="form.name" placeholder="请选择名称" :disabled="!form.type">
            <el-option v-for="machine in filteredMachines" :key="machine.value" :label="machine.label"
              :value="machine.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="正常" value="NORMAL" />
            <el-option label="故障" value="FAULT" />
            <el-option label="维护中" value="MAINTENANCE" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传图片" prop="imageFile">
          <el-upload ref="uploadRef" :auto-upload="false" :limit="1" :on-change="handleImageChange"
            :on-remove="handleImageRemove" accept="image/*">
            <el-button type="primary">选择图片</el-button>
            <template #tip>
              <div class="el-upload__tip">仅支持图片文件，单文件限制1个</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';
import { ElMessage, ElLoading, FormInstance, UploadInstance } from 'element-plus';
import { useMachineStore } from '@/stores/machine';
import { useUserStore } from '@/stores/user';
import { useAgriculturalDataStore } from '@/stores/agriculturalData';
import { useRouter } from 'vue-router';
import axios from '@/plugins/axios';

const router = useRouter();
const machineStore = useMachineStore();
const userStore = useUserStore();
const agriculturalDataStore = useAgriculturalDataStore();

const form = ref({
  number: '',
  type: '',
  name: '',
  status: '',
  url: '',
  ownerId: userStore.user?.id || 0,
});

const imageFile = ref<File | null>(null);
const formRef = ref<FormInstance>();
const uploadRef = ref<UploadInstance>();

const rules = {
  number: [{ required: true, message: '请输入机器编号', trigger: 'blur' }],
  type: [{ required: true, message: '请选择机器类型', trigger: 'change' }],
  name: [{ required: true, message: '请选择机器名称', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  imageFile: [{
    validator: (_: any, __: any, callback: (error?: Error) => void) => {
      if (!imageFile.value) {
        callback(new Error('请上传图片'));
      } else {
        callback();
      }
    },
    trigger: 'change',
  }],
};

const filteredMachines = computed(() => {
  const group = agriculturalDataStore.getAgriculturalMachines.find(g => g.title === form.value.type);
  return group ? group.options : [];
});

const onTypeChange = () => {
  form.value.name = ''; // 清空名称选择
};

const handleImageChange = (file: any) => {
  imageFile.value = file.raw;
  formRef.value?.validateField('imageFile');
};

const handleImageRemove = () => {
  imageFile.value = null;
  formRef.value?.validateField('imageFile');
};

const uploadImage = async () => {
  if (!imageFile.value) {
    ElMessage.error('请先选择图片');
    return null;
  }

  const formData = new FormData();
  formData.append('file', imageFile.value);

  const loading = ElLoading.service({
    lock: true,
    text: '图片上传中...',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  try {
    const response = await axios.post('/file', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    if (response.data.code === 200) {
      return response.data.data.url;
    } else {
      ElMessage.error('图片上传失败');
      return null;
    }
  } catch (error) {
    ElMessage.error('图片上传失败，网络错误');
    console.error(error);
    return null;
  } finally {
    loading.close();
  }
};

const submitForm = async () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      const url = await uploadImage();
      if (!url) return;

      form.value.url = url;
      try {
        await machineStore.addMachine(form.value);
        ElMessage.success('添加成功');
      } catch (error) {
        ElMessage.error('添加失败');
        console.error(error);
      }
    } else {
      ElMessage.warning('请填写所有必填项');
    }
  });
};
</script>

<style scoped>
.add-machine {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.add-card {
  border: 1px solid #ddd;
  border-radius: 8px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #606266;
}

.add-form {
  padding: 20px;
}
</style>